import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useRoles } from 'contexts/RolesContext';
import { usePlanType } from 'contexts/PlanTypeContext';
import { useAuth } from 'contexts/AuthContext';
// import { getSuperToken } from 'libs/utils'; // Optional, unused for now
import Storage from 'libs/storage';
import { SUPER_JWT_TOKEN } from 'config'; // Correct token key

const DebugTokenLogger = ({ token }) => (
  <div style={{
    position: 'fixed',
    top: 0,
    left: 0,
    padding: '1rem',
    backgroundColor: 'black',
    color: 'lime',
    zIndex: 9999,
    fontFamily: 'monospace',
    maxWidth: '100vw',
    overflowWrap: 'break-word',
  }}>
    <strong>SUPER_JWT_TOKEN:</strong><br />
    {token || 'No token found.'}
  </div>
);

const LoadingComponent = () => (
  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    <div>Loading...</div>
  </div>
);

export const PrivateRoute = ({ element: Component, ...rest }) => {
  const location = useLocation();
  const { isAuthenticated, user, isLoading } = useAuth();
  const allowedRoles = useRoles();
  const planType = usePlanType();

  if (isLoading) {
    return <LoadingComponent />;
  }

  // === EARLY VISUAL LOGGER using correct token key ===
  const superToken = Storage.getItem(SUPER_JWT_TOKEN);
  return <DebugTokenLogger token={superToken} />;

  // If/when you disable the logger, the full auth logic remains intact below

  if (!isAuthenticated) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  const requiresSuperAdmin = allowedRoles.length === 1 && allowedRoles.includes('superadmin');
  if (requiresSuperAdmin && !superToken) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  let allowed = isAuthenticated && user && allowedRoles.includes(user.role);

  if (planType && planType.length > 0) {
    allowed = allowed && planType.includes(user.account.planType);
  }

  if (!allowed) {
    return (
      <Navigate
        to="/dashboard"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  return <Component {...rest} />;
};